package org.rendao.auth.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.rendao.auth.dao.UserDetailDao;
import org.rendao.auth.data.UserDetailDO;
import org.rendao.constant.ConstantDefinition;
import org.rendao.dao.IGenericDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class UserDetailDaoImpl implements UserDetailDao {

	private IGenericDao<UserDetailDO> genericUserDao;

	public void setGenericUserDao(IGenericDao<UserDetailDO> genericUserDao) {
		this.genericUserDao = genericUserDao;
	}

	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Autowired
	private NamedParameterJdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(NamedParameterJdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public UserDetailDO getById(String id) {
		return genericUserDao.getById(id);
	}

	@Override
	public UserDetailDO save(UserDetailDO userDetailDO) {
		return genericUserDao.save(userDetailDO);
	}

	@Override
	public UserDetailDO update(UserDetailDO userDetailDO) {
		return genericUserDao.update(userDetailDO);
	}

	@Override
	public List<UserDetailDO> getAllAvailable() {
		return genericUserDao.getAllAvailable();
	}

	@Override
	public int softDelete(String id) {
		UserDetailDO user = genericUserDao.getById(id);
		String userId = user.getId();
		String sql = "delete from user_role where user_id = :user_id";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user_id", userId);
		jdbcTemplate.update(sql, params);
		
		sql = "update user set is_deleted = :is_deleted where id = :id";
		params.clear();
		params.put("id", userId);
		params.put("is_deleted", ConstantDefinition.IS_DELETED_TRUE);
		return jdbcTemplate.update(sql, params);
	}
}
